package com.bulletelc.apollopre.module.main.center;

import android.content.Context;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.constants.SPKey;
import com.bulletelc.apollopre.entity.OrderStateCountBean;
import com.bulletelc.apollopre.framework.BasePresenter;
import com.bulletelc.apollopre.utils.Base64Util;
import com.bulletelc.apollopre.utils.DateUtil;
import com.bulletelc.apollopre.utils.FileUtil;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.utils.SharedPreferencesUtil;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * author: lhl
 * date  : 2018/01/23
 * desc  : TODO
 */

public class CenterPresenter extends BasePresenter<CenterContract.View> implements CenterContract.Presenter {
    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void getSetting() {
        getSettingImp();
    }

    @Override
    public void getAvatar() {
        getUserAvatar();
    }

    @Override
    public void getOrderStateCount() {
        getOrderStateCountImp();
    }

    @Override
    public void postAvatar(Context context, String path) {
        postUserAvatar(context, path);
    }

    /**
     * 上传用户头像
     */
    private void postUserAvatar(Context context,String path) {
        // 获取图像格式后缀
        String ext = FileUtil.getFileExtension(path);
        // base64 补充
        String base64String = "data:image/" + ext + ";base64," + Base64Util.fileToBase64String(path);
        // 图片命名
        String fileName = DateUtil.filenameByDate(System.currentTimeMillis()) + "." + ext;
        // 封装json格式
        org.json.JSONObject obj = new org.json.JSONObject();
        org.json.JSONObject objSub = new org.json.JSONObject();
        JSONArray objArray = new JSONArray();
        try {
            objSub.put("name", fileName);
            objSub.put("base64_image", base64String);
            objArray.put(objSub);
            obj.put("entity_id", SharedPreferencesUtil.getString(context, SPKey.SP_USER_ID));
            obj.put("images", objArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(MediaType.parse(GlobalConfig.CONTENT_TYPE_JSON), obj.toString());
        OkGo.<String>post(NetWorkPath.POST_IMAGE_UPLOAD)
                .headers("Authorization", GlobalConfig.AUTH_HEAD + MyApplication.getToken())
                .upRequestBody(body)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parsePostAvatarData(response);
//                        LogUtil.i(response.body().toString());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorPostAvatar(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析用户上传头像数据
     */
    private void parsePostAvatarData(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                org.json.JSONObject obj = new org.json.JSONObject(response.body().toString());
                org.json.JSONObject objMeta = new org.json.JSONObject(obj.getString("meta"));
                // 操作成功
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code").toString())) {
                    if (isViewAttached()) {
                        getView().onSuccessPostAvatar(objMeta.getString("msg"));
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailPostAvatar(objMeta.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorPostAvatar(e.getMessage().toString());
                }

            }
        } else {
            if (isViewAttached()) {
                getView().onFailPostAvatar(response.body().toString());
            }
        }
    }

    /**
     * 获取头像
     */
    private void getUserAvatar() {
        OkGo.<String>get(NetWorkPath.GET_USER_AVATAR)
                .params("access_token", MyApplication.getToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseGetAvatar(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorGetAvatar(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析获取头像数据
     */

    private void parseGetAvatar(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject obj = new JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(obj.getString("meta"));
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code"))) {
                    JSONObject objData = new JSONObject(obj.getString("data"));
                    if (isViewAttached()) {
                        getView().onSuccessGetAvatar(objData.getString("thumbnail"));
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailGetAvatar(objMeta.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorGetAvatar(e.getMessage().toString());
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailGetAvatar(response.body().toString());
            }
        }
    }

    /**
     * 获取用户信息
     */
    private void getSettingImp() {
        OkGo.<String>get(NetWorkPath.GET_SETTING)
                .params("access_token", MyApplication.getToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //LogUtil.i(response.body().toString());
                        parseSetting(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorGetSetting(response.getException().toString());
                        }
                    }
                });
    }

    /**
     * 解析数据
     *
     * @param response
     */
    private void parseSetting(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                org.json.JSONObject object = new org.json.JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(object.getString("meta"));
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code").toString())) {
                    org.json.JSONArray dataArray = object.getJSONArray("data");
                    org.json.JSONObject objSub = new org.json.JSONObject(dataArray.getJSONObject(0).getString("profile"));
                    if (isViewAttached()) {
                        getView().onSuccessGetSetting(objSub.getString("name"));
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailGetSetting(objMeta.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorGetSetting("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailGetSetting(response.body().toString());
            }
        }
    }

    /**
     * 获取订单状态的数量
     */
    private void getOrderStateCountImp() {
        OkGo.<String>post(NetWorkPath.POST_ORDER_STATE_COUNT)
                .headers(NetWorkPath.HEADER_KEY_AUTH, MyUtil.getAuthToken())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseOrderStateCount(response);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (isViewAttached()) {
                            getView().onErrorGetOrderStateCount(response.getException().toString());
                        }
                    }
                });
    }


    /**
     * 解析订单状态的数量数据
     *
     * @param response
     */
    private void parseOrderStateCount(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                org.json.JSONObject object = new org.json.JSONObject(response.body().toString());
                JSONObject objMeta = new JSONObject(object.getString("meta"));
                if (GlobalConfig.HTTP_RESULT_SUCCESS.equals(objMeta.getString("code"))) {
                    Gson gson = new Gson();
                    OrderStateCountBean bean = gson.fromJson(object.getJSONObject("data").toString(), OrderStateCountBean.class);
                    if (isViewAttached()) {
                        getView().onSuccessGetOrderStateCount(bean);
                    }
                } else {
                    if (isViewAttached()) {
                        getView().onFailGetOrderStateCount(objMeta.getString("msg"));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                if (isViewAttached()) {
                    getView().onErrorGetOrderStateCount("数据解释错误");
                }
            }
        } else {
            if (isViewAttached()) {
                getView().onFailGetOrderStateCount(response.body().toString());
            }
        }
    }


}
